/*
 * RadioStreamer.h
 *
 *  Created on: Dec 15, 2011
 *      Author: shaohong
 */

#ifndef RADIOSTREAMER_H_
#define RADIOSTREAMER_H_

#include <pthread.h>
#include "RtpStreamer.h"
#include "RadioChannel.h"
#include "usageHelper.h"
#include "AppLogger.h"
#include "RadioStreamerStats.h"

#include <utility>
#include <string>
#include <list>
#include <iostream>

using namespace std;

namespace nmps {

class RadioStreamer {
public:

	RadioStreamer(RadioChannel radioChannel);
	virtual ~RadioStreamer();

	// start the mp3 downloading, transcoding, streaming, pipeline
	void startStreaming();

	void switchChannel(RadioChannel newChannel);

	// temporarily pause the RTP streamer streaming real audio to recipients
	void pauseStreaming();

	// let the RTP streamer continue streaming audio to recipients
	void resumeStreaming();

	// stop all the streaming related threads in this RadioStreamer
	void stopStreaming();

	// add the recipient identified by (IP, Port) couple
	void addRecipient(string clientIP, int clientPort);

	// remove the streaming recipient identified by (IP, Port) couple
	void removeReceipient(string clientIP, int clientPort);

	const list< pair<string, int> > * getRecipientList();

    RtpStreamer * getRtpStreamer() const;

    pthread_mutex_t getRtpStreamerMutex();

    void setRtpStreamer(RtpStreamer *rtpStreamer);

    void setRtpStreamerMutex(pthread_mutex_t rtpStreamerMutex);

    string toString();

    pthread_t getRadioStreamerThread();

	void addRecipients(list<pair<string, int>  > & recipientList);

	bool isPaused();
	bool isStoped();
	bool isStreamingStarted();

	bool isTranscodingStarted();


	RadioChannel getRadioChannel();

	volatile bool transcodingStarted;

	RadioStreamerStats stats; // some statistical info for this RadioStreamer

	//write the current statistics to history
	void writeStatsToHistory();

private:
    RadioChannel radioChannel;

	pthread_t downloadingThread;
	pthread_t transcodingThread;
	pthread_t rtpStreamingThread;

	RtpStreamer * rtpStreamer;

	volatile bool paused;	// whether the streamer is started and streaming
	volatile bool streamingStarted;	// streaming has started and not stopped
	volatile bool stopped;	// started and then stopped

	pthread_mutex_t rtpStreamerMutex; // the mutex to access rtpStreamer
};



struct Mp3TranscodingThreadParams{
	int readFD;	// the FD from which mp3 data can be read
	RadioStreamer * radioStreamer;
};

/**
 * Something to pass to the RTP streaming thread
 */
struct RptStreamingThreadParams{
	RadioStreamer * radioStreamer;

};

struct Mp3DownloadingThreadParams{
	int writeFD; // the FD to which the mp3 data can be written
	string streamServerLocation;
	RadioStreamer * radioStreamer;
};


} /* namespace nmps */
#endif /* RADIOSTREAMER_H_ */
